<template>
  <view class="container">
    <!-- 状态栏占位 -->
    <view :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @click="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <text class="nav-title">收货地址</text>
      <view class="nav-right"></view>
    </view>
    
    <!-- 地址列表 -->
    <view class="address-list" v-if="!loading">
      <template v-if="addressList.length > 0">
        <view 
          v-for="(address, index) in addressList" 
          :key="address.id"
          class="address-item"
          :class="{ 'address-item-default': address.isDefault === 1 }"
          @click="selectAddress(address)"
        >
          <view class="address-content">
            <view class="address-header">
              <view class="address-name-phone">
                <text class="address-name">{{ address.receiverName }}</text>
                <text class="address-phone">{{ address.receiverPhone }}</text>
              </view>
              <view v-if="address.isDefault === 1" class="default-tag">默认</view>
            </view>
            <view class="address-detail">
              {{ address.province }} {{ address.city }} {{ address.district }} {{ address.detailAddress }}
            </view>
          </view>
          <view class="address-actions">
            <view class="action-item" @click.stop="setDefaultAddress(address)">
              <uni-icons :type="address.isDefault === 1 ? 'checkbox-filled' : 'circle'" size="18" color="#FF8C42"></uni-icons>
              <text>默认地址</text>
            </view>
            <view class="action-divider"></view>
            <view class="action-item" @click.stop="editAddress(address)">
              <uni-icons type="compose" size="18" color="#666"></uni-icons>
              <text>编辑</text>
            </view>
            <view class="action-divider"></view>
            <view class="action-item" @click.stop="deleteAddress(address)">
              <uni-icons type="trash" size="18" color="#666"></uni-icons>
              <text>删除</text>
            </view>
          </view>
        </view>
      </template>
      
      <!-- 空状态 -->
      <view v-else class="empty-state">
        <image class="empty-icon" src="/static/placeholder.png" mode="aspectFit"></image>
        <text class="empty-text">暂无收货地址</text>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <uni-load-more status="loading" :contentText="{ contentdown: '加载中...' }"></uni-load-more>
    </view>
    
    <!-- 底部按钮 -->
    <view class="footer">
      <button class="add-btn" @click="addNewAddress">
        <uni-icons type="plusempty" size="18" color="#FFFFFF"></uni-icons>
        <text>新增收货地址</text>
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useUserStore } from '@/store/user';
import http from '@/utils/http/http.js';

const userStore = useUserStore();
const statusBarHeight = ref(0);
const addressList = ref([]);
const loading = ref(true);
const fromCheckout = ref(false);

// 获取状态栏高度
const getStatusBarHeight = () => {
  try {
    statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight || 0;
  } catch (e) {
    console.error('获取系统信息失败:', e);
    statusBarHeight.value = 0;
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 获取地址列表
const fetchAddressList = async () => {
  if (!userStore.isLoggedIn || !userStore.token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
    return;
  }
  
  loading.value = true;
  
  try {
    const response = await http.get('/api/address/list', {
      header: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    console.log("response",response.data);
    if (response.code === 200) {
      addressList.value = response.data || [];
    } else {
      uni.showToast({
        title: response.message || '获取地址列表失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取地址列表失败:', error);
    uni.showToast({
      title: '获取地址列表失败，请重试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 选择地址（从结算页进入时使用）
const selectAddress = (address) => {
  if (fromCheckout.value) {
    // 将选中的地址传回结算页
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2];
    
    if (prevPage && prevPage.route.includes('checkout')) {
      // 设置上一页的选中地址
      prevPage.$vm.selectedAddress = address;
      uni.navigateBack();
    }
  }
};

// 设置默认地址
const setDefaultAddress = async (address) => {
  if (address.isDefault === 1) {
    return; // 已经是默认地址，不需要操作
  }
  
  try {
    const response = await http.post(`/api/address/set-default/${address.id}`, {}, {
      header: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200) {
      // 更新本地地址列表
      addressList.value = addressList.value.map(item => ({
        ...item,
        isDefault: item.id === address.id ? 1 : 0
      }));
      
      uni.showToast({
        title: '设置默认地址成功',
        icon: 'success'
      });
    } else {
      uni.showToast({
        title: response.message || '设置默认地址失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('设置默认地址失败:', error);
    uni.showToast({
      title: '设置默认地址失败，请重试',
      icon: 'none'
    });
  }
};

// 编辑地址
const editAddress = (address) => {
  uni.navigateTo({
    url: `/pages/address/address-edit?id=${address.id}`
  });
};

// 删除地址
const deleteAddress = (address) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该收货地址吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await http.delete(`/api/address/${address.id}`, {
            header: {
              'Authorization': `Bearer ${userStore.token}`
            }
          });
          
          if (response.code === 200) {
            // 从本地列表中移除
            addressList.value = addressList.value.filter(item => item.id !== address.id);
            
            uni.showToast({
              title: '删除地址成功',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: response.message || '删除地址失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('删除地址失败:', error);
          uni.showToast({
            title: '删除地址失败，请重试',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 新增地址
const addNewAddress = () => {
  uni.navigateTo({
    url: '/pages/address/address-edit'
  });
};

// 页面加载
onMounted(() => {
  getStatusBarHeight();
  
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  if (currentPage && currentPage.options) {
    fromCheckout.value = currentPage.options.from === 'checkout';
  }
  
  // 获取地址列表
  fetchAddressList();
  
  // 监听页面显示，用于编辑后刷新列表
  uni.$on('addressUpdated', fetchAddressList);
});

// 页面卸载
onUnmounted(() => {
  uni.$off('addressUpdated');
});
</script>

<style>
.container {
  padding-bottom: 120rpx;
  background-color: #FFF9F2;
  min-height: 100vh;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 88rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #FFE6CC;
  padding: 0 20rpx;
}

.nav-back, .nav-right {
  width: 80rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

/* 地址列表 */
.address-list {
  padding: 20rpx;
}

.address-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.address-item-default {
  border-left: 6rpx solid #FF8C42;
}

.address-content {
  padding: 30rpx;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.address-name-phone {
  display: flex;
  align-items: center;
}

.address-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-right: 20rpx;
}

.address-phone {
  font-size: 28rpx;
  color: #666;
}

.default-tag {
  font-size: 22rpx;
  color: #fff;
  background-color: #FF8C42;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.address-detail {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
}

.address-actions {
  display: flex;
  border-top: 1rpx solid #f5f5f5;
  height: 80rpx;
}

.action-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #666;
}

.action-item text {
  margin-left: 8rpx;
}

.action-divider {
  width: 1rpx;
  height: 40rpx;
  background-color: #f5f5f5;
  align-self: center;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 加载状态 */
.loading-state {
  padding: 40rpx 0;
}

/* 底部按钮 */
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.add-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80rpx;
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 140, 66, 0.3);
}

.add-btn text {
  margin-left: 8rpx;
}
</style>
